package com.kly.job;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.constants.RedisConstant;
import com.kly.domain.vo.PictureVO;
import com.kly.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.kly.constants.RedisConstant.PICTURE_PAGE_KEY;

/**
 * @author admin
 * @date 2025/4/20
 */
@Slf4j
@Component
public class CacheWarm {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private PictureService pictureService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void cacheWarm() {
        log.info("缓存预热");
        Map<String, Page<PictureVO>> stringPageMap = pictureService.listPictureVOByPage();
        for (Map.Entry<String, Page<PictureVO>> entry : stringPageMap.entrySet()) {
            String key = PICTURE_PAGE_KEY + entry.getKey();
            Page<PictureVO> value = entry.getValue();
            int randomTTL = RedisConstant.THIRTY_TIME_TTL_LONG + RandomUtil.randomInt(1, 5);
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),randomTTL , TimeUnit.MINUTES);
        }
    }
}
